#include <getopt.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "util.h"
#include "server.h"

#define VERSION "0.0.1"

Server* server;

void
sigchld(int unused)
{
    /* We should be able to remove this function in favor of a simple
     *     signal(SIGCHLD, SIG_IGN);
     * but the Xwayland implementation in wlroots currently prevents us from
     * setting our own disposition for SIGCHLD.
     */
    if (signal(SIGCHLD, sigchld) == SIG_ERR)
        die("can't install SIGCHLD handler:");
    while (0 < waitpid(-1, NULL, WNOHANG))
        ;
}

void
quitsignal(int signo)
{
    server_quit(server);
}

int main(int argc, char** argv)
{
    char *startup_cmd = NULL;
    int c;

    while ((c = getopt(argc, argv, "s:hv")) != -1) {
        if (c == 's')
            startup_cmd = optarg;
        else if (c == 'v')
            die("dwl " VERSION);
        else
            goto usage;
    }
    if (optind < argc)
        goto usage;

    /* Wayland requires XDG_RUNTIME_DIR for creating its communications socket */
    if (!getenv("XDG_RUNTIME_DIR"))
        die("XDG_RUNTIME_DIR must be set");
//    setup();

    server = server_create();
    sigchld(0);
    signal(SIGINT, quitsignal);
    signal(SIGTERM, quitsignal);

    server_run(server, startup_cmd);
    server_free(server);

//    run(startup_cmd);
//    cleanup();
    return EXIT_SUCCESS;

usage:
    die("Usage: %s [-v] [-s startup command]", argv[0]);
}
